<template>
  <div class="shop-home flow-box">
    <div class="fiexdTabs">
    <van-search
      v-model="valueKey"
      background="none"
      @input="onInput"
      @clear="onClear"
      @search="onSearch"
      placeholder="请输入搜索关键词"
    />
    <van-tabs
      :active="typeIndex"
      @click="changeType"
      background="none"
      :border="false"
      title-active-color="#000000"
      title-inactive-color="#979999"
    >
      <van-tab v-for="(item, index) in tabList" :key="index" :name="{item:item,currIndex:index}" :title="item.categoryName"></van-tab>

    </van-tabs>
    </div>
    <!-- 列表  -->
    <van-pull-refresh id="pullList" :class="dataList.length>0?'':'notDataListBox'"
        v-model="isLoading"
        @refresh="onRefresh"
        :success-duration="800"
        success-text="加载成功"
        loading-text="加载中..."
          style="min-height: 50vh;"
      >
        <van-list
          v-if="haveData == 2"
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onBottomLoad"
          :offset="150"
          :immediate-check="false"
        >
          <div class="data-list-box" id="data-list-box" v-if="dataList.length > 0">
            <div
              class="data-item"
              v-for="(item, index) in dataList"
              @click="openModalDe(item)"
              :style="{ width: boxWidth + 'px' }"
              :key="index"
            >
              <img
                class="data-cover"
                :src="item.mainPhoto"
                :style="{ width: '100%', height: item.imgHeight + 'px' }"
              />
              <div class="dataInfo">
                <div class="data-name">{{ item.goodsName }}</div>
                <div class="data-jieshao">{{item.browsingVolume}}人看过</div>
                <div class="data-price">¥<span>{{item.goodsPrice}}</span></div>
              </div>
            </div>
            <div class="data-item"></div>
          </div>
          <div id="data-list-box" v-else>
            <noData :tipsText="tipsText"></noData>
          </div>
        </van-list>
      </van-pull-refresh>
  </div>
</template>

<script>
import noData from "@/components/noData"
import $api from "@/api/index";
export default {
  name: "ShopHome",
  components: {
    noData
  },
  data() {
    return {
      tipsText:'此分类下无商品',
      //loadFlag:[false,false,false],
      valueKey: "",
      tabList: [
        {categoryId:'', categoryName: "推荐" }
      ],
      typeIndex: 0, //分类索引
      dataList: [], //列表数据
      haveData: 0, //是否有数据，1=无，2=有，0=页面还未初始化
      hasNextPage:true,
      categoryId:'',
      goodsName:'',
      pageIndex: 0, //页码
      pageSize: 10, //每页加载数据数量
      isLoading: false, //下拉刷新进行中，请求开始true, 请求完成false，用于下拉刷新组件van-pull-refresh
      loading: false, //上拉加载更多中，上拉触底时自动变成true, 请求完成设置为false, 用于列表组件van-list
      finished: false, //上拉加载是否加载完最后一页数，用于组件van-list
      itemCount: 0, //上一次加载完成后的瀑布流item个数
      lastRowHeights: [0, 0], //最后一行标签的顶部间距+高度，2列
      boxMargin: 12, //每个item之间的边距
      boxWidth: 165, //每个item宽度
      searchState:false,
      allow:true
    };
  },
  methods:{
      onCagegoryList(){
          let params = {
            cid:'1394185329937879040'
          }
          $api.shopApi.cagegoryList(params).then((res)=>{
              //console.log(res)
              if(res.status == 10000){
              this.tabList = [...this.tabList, ...res.data]
              }
          })
      },
      changeType(datas) {
          this.searchState = false
          // this.goodsName = ''
          let parentEle = document.getElementById('data-list-box');
          let pull = document.getElementsByClassName("van-pull-refresh");
          parentEle.scrollTop = 0
          pull.scrollTop = 0
          parentEle.style.height = 'calc(100vh - 300px)'
          //切换类型
          //this.typeIndex = datas.currIndex;
          //if (this.typeIndex == datas.currIndex) return;
          this.$toast.loading({
              message: "加载中...",
              duration: 0,
          });
          this.categoryId = datas.item.categoryId
          this.dataList = [];
          this.pageIndex = 0; //重置第一页
          this.hasNextPage = false
          setTimeout(() => {
            this.getDataList();
          }, 1000);
      },
      onRefresh(){ //下拉刷新
          //console.log('下拉刷新')
          // if (this.isLoading) return; //还在请求中，返回
          this.pageIndex = 0; //重置第一页
          this.dataList = []
          this.isLoading = true; //开始加载
          this.finished = false; //上拉加载"所有数据已经完成"标识 重置为false
          //接口请求
          this.getDataList();
      },
      onBottomLoad(){ //上拉加载更多
          if(this.hasNextPage){
            this.pageIndex++;  //还有下一页
            if (this.finished) return; //说明所有数据已经加载完毕，返回
            this.getDataList(); //下一页数据请求中
          }else{
            this.isLoading = false; //停止
            this.loading = true;//停止
            this.finished = true;//此时不会触发load事件
          }
      },
      onInput(val){
        this.goodsName = val
      },
      onClear(){
        this.searchState = true
          this.$toast.loading({
              message: "搜索中...",
              duration: 0,
          });
          this.pageIndex = 0
        this.goodsName = ''
        this.pageIndex = 0; //重置第一页
        this.isLoading = true; //开始加载
        this.finished = false; //上拉加载"所有数据已经完成"标识 重置为false
        this.dataList = []
        this.getDataList();
      },
      onSearch(val){
          this.searchState = true
          this.$toast.loading({
              message: "搜索中...",
              duration: 0,
          });
          this.pageIndex = 0
        this.goodsName = val
        this.pageIndex = 0; //重置第一页
        this.isLoading = true; //开始加载
        this.finished = false; //上拉加载"所有数据已经完成"标识 重置为false
        this.dataList = []
        this.getDataList();
      },
      //数据请求
      getDataList(){
          let params = {
            goodsName:this.goodsName,
            categoryId:this.categoryId,
            page:this.pageIndex,
            size:this.pageSize,
            cid:'1394185329937879040'
          }
          $api.shopApi.goodsList(params).then((res)=>{
              let list = res.data.content ? res.data.content: [];
              this.hasNextPage = res.data.hasNextPage
              if (list.length > 0){
                  //从list中取pageSize条数据出来
                  var tempList = [];
                  for (let i = 0; i < this.pageSize; i++){
                      if (list.length > 0){
                          let tempIndex = parseInt(Math.random() * 1000) % list.length;
                          tempList.push(list[tempIndex]);
                          list.splice(tempIndex, 1);
                      }
                  }
                  this.loading = true;//加载
                  this.finished = false;
                  this.loadImagesHeight(tempList); //模拟预加载图片，获取图片高度
              }
              else {
                if(res.data.totalElements == 0){
                  this.finished = true;
                  this.isLoading = false; //下拉刷新请求完成
                  this.loading = false; //上拉加载更多请求完成
                  this.$toast.clear();
                  return
                }else{
                  this.loading = true; //开始
                  this.finished = false; //开始load
                  this.loadImagesHeight(list); //处理数据
                }
              }
          }).catch((res)=>{
              console.log("..fail: ", res);
              this.$toast.clear();
              this.isLoading = false; //下拉刷新请求完成
              this.loading = false; //上拉加载更多请求完成
          })
      },
      loadImagesHeight(list){
          var count = 0; //用来计数，表示是否所有图片高度已经获取
          if(list.length > 0 ){
            list.forEach((item, index)=>{
              //创建图片对象，加载图片，计算图片高度
              var img = new Image();
              img.src = item.mainPhoto;
              img.onload = img.onerror = (e)=>{
                  count++;
                  if (e.type == 'load'){ //图片加载成功
                      //计算图片缩放后的高度：图片原高度/原宽度 = 缩放后高度/缩放后宽度
                      list[index].imgHeight = Math.round(img.height * this.boxWidth / img.width);
                      // console.log('index: ', index, ', load suc, imgHeiht: ', list[index].imgHeight);
                  }
                  else{ //图片加载失败，给一个默认高度50
                      list[index].imgHeight = 50;
                      console.log("index： ", index, "， 加载报错：", e);
                  }

                  //加载完成最后一个图片高度，开始下一步数据处理
                  if (count == list.length){
                      this.resolveDataList(list);
                  }
              }
            })
          }else{
              this.$toast.clear();
              this.isLoading = false; //下拉刷新请求完成
              this.finished = true;
              if(this.searchState == true){
                this.$toast("未匹配到相关的商品");
              }
          }
      },
      resolveDataList(list){ //处理数据
          //下拉刷新，清空原数据
          if (this.pageIndex <= 1){
              this.itemCount = 0;
              //this.dataList = [];
              this.lastRowHeights = [0, 0]; //存储每列的最后一行高度清0
          }
          this.dataList = [...this.dataList, ...list];

          //合并新老两个数组数据
          //判断页面是否有数据
          this.haveData = this.dataList.length > 0 ? 2 : 1;

          this.$nextTick(()=>{
              setTimeout(()=>{
                  //渲染完成，计算每个item宽高，设置标签坐标定位
                  this.setItemElementPosition();
                  this.isLoading = false; //下拉刷新请求完成
                  this.loading = false; //上拉加载更多请求完成
              }, 1000)
          });
      },
      //获取每个item标签高度，设置item的定位
      setItemElementPosition(){
        if(this.allow){//防止getElementsByClassName报错
          let parentEle = document.getElementById('data-list-box');
          let boxEles = parentEle.getElementsByClassName("data-item");
          if(boxEles && boxEles.length > 0){
            for (let i = this.itemCount; i < boxEles.length; i++){
                let tempEle = boxEles[i];
                //上一个标签最小高度的列索引
                let curColIndex = this.getMinHeightIndex(this.lastRowHeights);
                let boxTop = this.lastRowHeights[curColIndex] + this.boxMargin;
                let boxLeft = curColIndex * (this.boxWidth + this.boxMargin) + this.boxMargin;
                tempEle.style.left = boxLeft + 'px';
                tempEle.style.top = boxTop + 'px';
                this.lastRowHeights[curColIndex] = boxTop + tempEle.offsetHeight;

                // console.log('i = ', i, ', boxTop: ', boxTop, ', eleHeight: ', tempEle.offsetHeight);
            }

            this.itemCount = boxEles.length;

            //修改父级标签的高度
            let maxHeight = Math.max.apply(null, this.lastRowHeights);
            parentEle.style.height = maxHeight + 'px';
            parentEle.style.paddingBottom = '20px';

            this.$toast.clear();
            //console.log("...boxEles: ", boxEles.length, ", maxH: ", maxHeight);
          }
        }
      },
      //获取数组中最小值的索引
      getMinHeightIndex(arr){
          var minHeight = Math.min.apply(null, arr);
          for (let i = 0; i < arr.length; i++){
              if (arr[i] == minHeight){
                  return i;
              }
          }
      },
      /**
       * 跳转详情
       */
      openModalDe(item){
        //console.log(item)
        this.$router.push({path:"/goodsDetail",query:{goodsId:item.goodsId,source:'2'}})
      }
  },
  created() {
    this.onCagegoryList()
    this.$toast.loading({
      message: "加载中...",
      duration: 0,
    });
    let screenWidth = document.body.offsetWidth; //屏幕宽度
    this.boxWidth = (screenWidth - this.boxMargin * 3) / 2; //每个item的宽度
    this.onRefresh();
  },
  activated(){
  },
  
  beforeRouteEnter(to, from, next) {
      next(vm => {
        vm.allow = true
        document.getElementById('pullList').scrollTop = to.meta.scollTopPosition;
        //console.log(vm.hasNextPage)
        if(document.getElementById('pullList').scrollTop != 0){
          if(vm.hasNextPage){
            vm.isLoading = true
            vm.finished = false
            vm.loading = false;
          }
        }
      });
  },
  beforeRouteLeave(to, from, next) {
      this.allow = false
      if(from.meta.keepAlive) {
        from.meta.scollTopPosition = document.getElementById('pullList').scrollTop;
      }
      next();
  }
};
</script>

<style lang="scss" scoped>
@import "../../styles/variables";
.shop-home {
  background: #f2f5f4;
  width: 100vw; height:calc(100vh - 300px);
  padding-top: 200px;
  overflow: hidden;
  .van-pull-refresh{
    overflow-y: scroll;
  }
  .fiexdTabs{
    background: #f2f5f4;
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 4;
    height: 200px;
  }
  .van-search {
    background: none;
  }
  .van-search__content {
    background: #e6ebe9;
  }
  .van-list{
    height: calc(100vh - 300px);
    /*overflow: auto;*/
  }
  .data-list-box {
    position: relative;
    min-height: calc(100vh - 450px);
    /*height: calc(100vh - 450px);*/
    background: #f2f5f4;
  }
  .data-item {
    height: auto;
    position: absolute;
    left: -1000px;
    //animation: data-item-ani 0.4s;
    //transition: left 0.6s, top 0.6s;
    //transition-delay: 0.1s;
    overflow: hidden;
    border-radius: 8px 8px 0px 0px;
    img{
      display: block;
    }
  }
  .dataInfo {
    background-color: #ffffff;
    padding: 15px 20px;
    line-height: 40px;
    border-radius: 0px 0px 8px 8px;
    overflow: hidden;
    .data-name {
      font-size: 28px;
      color: #323232;
      text-align: left;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .data-jieshao {
      padding-top: 5px;
      color: #8e7526;
      font-size: 20px;
    }
    .data-price {
      padding-top: 5px;
      color: #db1919;
      span {
        font-size: 40px;
      }
    }
  }
}
/* 隐藏滚动条 */
.type-list::webkit-scrollbar {
  dispplay: none;
}

/* 列表数据样式 */
@keyframes data-item-ani{
    0% { transform: scale(0.5); }
    100% { transform: scale(1); }
}
</style>
